const express = require('express');
const router = express.Router();
const db = require('../config/db');

// 点赞帖子
router.post('/posts/:id/like', (req, res) => {
  const postId = req.params.id;
  const userId = req.user.id;

  db.query(
    'INSERT INTO likes (user_id, post_id) VALUES (?, ?)',
    [userId, postId],
    (error) => {
      if (error) {
        if (error.code === 'ER_DUP_ENTRY') {
          return res.status(400).json({ error: '已经点赞过了' });
        }
        return res.status(500).json({ error: error.message });
      }
      res.json({ message: '点赞成功' });
    }
  );
});

// 取消点赞
router.delete('/posts/:id/like', (req, res) => {
  const postId = req.params.id;
  const userId = req.user.id;

  db.query(
    'DELETE FROM likes WHERE user_id = ? AND post_id = ?',
    [userId, postId],
    (error) => {
      if (error) {
        return res.status(500).json({ error: error.message });
      }
      res.json({ message: '取消点赞成功' });
    }
  );
});

// 获取帖子点赞数
router.get('/posts/:id/likes', (req, res) => {
  const postId = req.params.id;

  db.query(
    'SELECT COUNT(*) as likeCount FROM likes WHERE post_id = ?',
    [postId],
    (error, results) => {
      if (error) {
        return res.status(500).json({ error: error.message });
      }
      res.json({ count: results[0].likeCount });
    }
  );
});

module.exports = router; 